﻿using System.IO;
using Logger;
using SocketCore.Network;
using System.Drawing;

namespace SocketCore.Decoder
{
    public class ManualMessageDecoder : IMessageDecoder
    {
        public Message Decode(MemoryStream buffer)
        {
            int type = -1;
            bool bInternal;
            object data;
            try
            {
                type = SerializerHelper.ReadInt(buffer);
                bInternal = SerializerHelper.ReadBoolean(buffer);

                if (type == (int)PackageTypeEnum.Ascii || type == (int)PackageTypeEnum.Heartbeat)
                {
                    data = SerializerHelper.ReadString(buffer);
                }
                else
                {
                    byte[] arrData = SerializerHelper.ReadBytes(buffer);
                    switch(type)
                    {
                        case (int)PackageTypeEnum.Bitmap:
                            {
                                data = new Bitmap(new MemoryStream(arrData));
                            }
                            break;
                        case (int)PackageTypeEnum.MemoryStream:
                            data = new MemoryStream(arrData);
                            break;
                        default:
                            data = arrData;
                            break;
                    }
                    
                }
                Message message = new Message((PackageTypeEnum)type, bInternal, data);
                return message;
            }
            catch (System.Exception ex)
            {
                Log.WriteLog(string.Concat(new object[] { "Error when decoding type: ", type, ", exception: ", ex }));
            }
            return null;
        }
    }

 

}
